package com.yishusmt.mobsmt.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.RestController;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * 使用WebSocket通信
 *
 * @author zhangyi
 * @date 2018/8/8 15:11
 */
@RestController
@ServerEndpoint(value = "/message")
@Api(description = "及时通讯模块")
public class WebSocketController {

    /**
     * 查看当前的在线个数
     */
    private static int currentCount = 0;

    /**
     * 复制一个副本对去进行set对象
     */
    private static CopyOnWriteArraySet<WebSocketController> webSocketSet = new CopyOnWriteArraySet<>();

    /**
     * 与客户端连接时候，发送给客户端数据
     */
    private Session session;

    /**
     * 调用成功时候的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);
        System.out.println("有新的连接加入");
    }

    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
        System.out.println("有一个线程关闭");
    }

    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        System.out.println("客户端发送来的消息：" + message);
        WebSocketController.sendInfo(message);
    }

    /**
     * 群发自定义消息
     */
    public static void sendInfo(String message) throws IOException {
        for (WebSocketController item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                continue;
            }
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发送错误");
        error.printStackTrace();
    }


    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    public Integer getCurrentCount() {
        return currentCount;
    }

    public static synchronized void addCurrent() {
        currentCount++;
    }

    public static synchronized void subCurrent() {
        currentCount--;
    }

}
